<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\approval;

use think\facade\Db;
use app\common\repositories\BaseRepository;
use app\common\dao\approval\ApprovalReceivesDao;
use app\common\repositories\work\WorkExpendApplyRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;

/**
 * Class ApprovalReceivesRepository
 * @package app\common\repositories\poster
 * @mixin ApprovalReceivesDao
 */
class ApprovalReceivesRepository extends BaseRepository
{

    public function __construct(ApprovalReceivesDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, $propertyId)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'submitUserInfo' => function ($query) {
                    $query->bind(['submit_username' => 'username']);
                }
            ])
            ->order('id', 'desc')
            ->append(['source_info'])
            ->select();
        /** @var ApprovalConfigRepository $configRepository */
        $configRepository = app()->make(ApprovalConfigRepository::class);
        $flowTypeBData = $configRepository::FLOW_TYPE_B;
        $flowTypeCData = $configRepository::FLOW_TYPE_C;
        $flowTypeData = array_merge($flowTypeBData, $flowTypeCData);
        foreach ($list as $k => $v) {
            $list[$k]['flow_name'] = ($v['submit_username'] ?? '') . ' 的 ' . ($flowTypeData[$v['flow_type']] ?? '') . ' 申请 ';
            $list[$k]['flow_type'] = ($flowTypeData[$v['flow_type']] ?? '');
        }
        return compact('count', 'list');
    }

    /**
     * 添加流程 审核记录
     * @param $propertyId
     * @param  $flowInfo
     * @param array $data 用户 ID
     * @param int $verifyType 1审核 2 确认 3抄送
     * @param int $status 1待审核 2审核中 3审核失败 7 无需审核 9审核通过
     * @return int
     *
     * @author Amos
     * 2024-05-23 08:03
     */
    public function batchAdd($propertyId, $flowInfo, array $data, int $verifyType = 1, int $status = 7)
    {
        $insertData = [];
        foreach ($data as $k => $v) {
            $insertData[] = [
                'is_check' => 1, ## 未阅读
                'present_uid' => $v,
                'status' => $status,
                'property_id' => $propertyId,
                'flow_id' => $flowInfo['id'],
                'verify_type' => $verifyType,
                'is_type' => $flowInfo['is_type'],
                'source_id' => $flowInfo['source_id'],
                'flow_type' => $flowInfo['flow_type'],
                'submit_uid' => $flowInfo['submit_uid'],
            ];
        }
        return $this->dao->insertAll($insertData);
    }

    public function addInfo(array $data, int $propertyId = 1, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $res = $this->dao->create($data);
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'APPROVAL.RECEIVES.ADD', $data);
            return $res;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'APPROVAL.RECEIVES.EDIT', $data);
            return $this->dao->update($info['id'], $data);
        });
    }

    public function getDetail(int $id)
    {
        return $this->dao->getSearch(['id' => $id])
            ->find();
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ]);
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0)
    {
        /** @var PropertyUsersLogRepository $repository */
        $repository = app()->make(PropertyUsersLogRepository::class);
        $repository->addInfo($info['property_id'], $userId, 'APPROVAL.RECEIVES.DEL', $info);
        $this->dao->delete($info['id']);
    }

    public function approvalSubmitInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'APPROVAL.RECEIVES.APPROVAL', $data);
            $infoData['status'] = $data['status'];
            if ($data['remark']) {
                $infoData['remark'] = $data['remark'];
            }
            $infoData['audit_time'] = date("Y-m-d H:i:s");
            $resInfo = $this->dao->update($data['receives_id'], $infoData);

            /** @var ApprovalFlowRepository $approvalFlowRepository */
            $approvalFlowRepository = app()->make(ApprovalFlowRepository::class);
            $flowInfo = $approvalFlowRepository->get($info['flow_id']);
            $flowData = $param = [];
            if ($data['status'] == 9) {
                ## 审核成功   查看还有没有 没有审核数的数据，如果有，继续下一个审核， 如果没有，修改当条数据为己审核
                $receivesInfo = $this->dao->getSearch([])
                    ->where('id', '<>', $info['id'])
                    ->where('status', 'in', [1, 2])
                    ->where('flow_id', $info['flow_id'])
                    ->where('verify_type', 1)
                    ->order('id', 'asc')
                    ->find();
                if ($receivesInfo) {
                    $flowData['present_uid'] = $receivesInfo['present_uid'];
                    if ($flowInfo['status'] == 1) {
                        $flowData['status'] = 2;
                    }
                    $param['status'] = 2; ## 审核中
                } else {
                    $flowData['status'] = 9;
                    $param['status'] = 2; ## 审核己完成
                }
            } else if ($data['status'] == 3) {
                $flowData['status'] = 3;
                $param['status'] = 2; ## 审核失败
            }
            ## 更新 流程数据
            $approvalFlowRepository->editInfo($flowInfo, $flowData, $userId);

            $sourceInfo['id'] = $info['source_id'];
            $sourceInfo['property_id'] = $info['property_id'];

            if ($info['flow_type'] == 'expend_apply') {
                ## 报销流程
                /** @var WorkExpendApplyRepository $workExpendApplyRepository */
                $workExpendApplyRepository = app()->make(WorkExpendApplyRepository::class);
                $workExpendApplyRepository->editInfo($sourceInfo, $param, $userId);
            }

            return $resInfo;
        });
    }


}